<?php

/**
 * 单进程模型
 * Class SingleProcess
 */
class SingleProcess
{
    protected $socket = null;

    public $onConnect = null;

    public $onMessage = null;

    public function __construct(string $address)
    {
        $this->socket = stream_socket_server($address);
    }

    public function start()
    {
        while (true) {
            $conn = stream_socket_accept($this->socket);

            if ($conn && is_callable($this->onConnect)) {
                call_user_func($this->onConnect, $conn);
            }

            $data = fread($conn, 65535);

            if (!empty($data) && is_callable($this->onMessage)) {
                call_user_func($this->onMessage, $conn, $data);
            }
        }
    }
}

$worker = new SingleProcess('tcp://0.0.0.0:9800');

$worker->onConnect = function ($fd) {
    echo '连接进来' . (int)$fd;
};

$worker->onMessage = function ($fd, $data) {
    echo '传了参数过来'.$data;
};

$worker->start();